<?php

class pos_orderController extends commonController {
    /**
     *    $where = array('AND'=>array('='=>array('order_no' => $exp['shop_express_no'],'shop_no' => $exp['shop_no'],'status' => 1,'isdeleted' => 0)));
     *    $data = $this->model->getItemByOther($where, 'tip_list'); 多次追加小费
     */
    public function GetOrderInfoAction()
    {
        $getOrderData = file_get_contents("php://input");
        $log = new Logging();
        $log->lfile('ReturnPosOrderData');
        $log->lwrite('reception:' . $getOrderData);
        $orderDatas = json_decode($getOrderData, true);
        $checkCode = md5('shjieta');
        $checkCode = strtoupper(substr($checkCode, 0, 16));
        if ($checkCode !== $orderDatas['check_code']) {
            $resule = json_encode(['errcode' => 1, 'errormsg ' => '校验码错误'], JSON_UNESCAPED_UNICODE);
            $orderDatasT = json_encode($orderDatas, JSON_UNESCAPED_UNICODE);
            $log->lwrite('reception:' . $orderDatasT.'response:'.$resule);
            echo $resule;
            exit;
        }

        if($orderDatas['version'] == 10) {
            $order_no = $orderDatas['order_no'];
            if(!$order_no){
                $resule = json_encode(['errcode' => 1, 'errormsg ' => '订单编号不可空'], JSON_UNESCAPED_UNICODE);
                $orderDatasT = json_encode($orderDatas, JSON_UNESCAPED_UNICODE);
                $log->lwrite('reception:' . $orderDatasT.'response:'.$resule);
                echo $resule;
                exit;
            }



            $sql_id = "select max(id) oid from orders where order_no = '$order_no'";
            $maxID = $this->model->getAny($sql_id);
            $oid = '';
            if (!empty($maxID)) {
                while ($row_id = mysqli_fetch_array($maxID, MYSQLI_ASSOC)) {
                    $oid = $row_id['oid'];
                }
            }else{
                $resule = json_encode(['errcode' => 1, 'errormsg ' => '订单不存在'], JSON_UNESCAPED_UNICODE);
                $orderDatasT = json_encode($orderDatas, JSON_UNESCAPED_UNICODE);
                $log->lwrite('reception:' . $orderDatasT.'response:'.$resule);
                echo $resule;
                exit;
            }

            $sql = "select a.distance,a.id,a.shop_no,a.customre_memo,a.seller_remarks,a.shop_name,a.ph_no,a.order_no,a.express_type,a.status,a.buyer,a.buyer_mobile,a.receiver,a.receiver_tel,a.receiver_address,c.longitude,c.latitude from orders as a left join xd_store as c ON a.shop_no = c.store_id where a.id = $oid AND a.order_no = '$order_no'";
            $orderRes = $this->model->getAny($sql);
            $data = [];
            if (!empty($orderRes)) {
                while ($row = mysqli_fetch_array($orderRes, MYSQLI_ASSOC)) {
                    $data = $row;
                }
            }


            if($data && is_array($data) && count($data) > 0){
                if(!$data['buyer_mobile']){
                    unset($data['buyer_mobile']);
                }
                $ph_no = $data['ph_no'];
                $sql_exp = "select status as bstatus,shop_delivery_time,express_mobile,shop_delivery_time ,express_fee,shop_express_remark,shop_remark,push_response_data,tip ,tip_remark 
 from orders_express  where ph_no = '$ph_no' order by createdt desc limit 1";
                $Res_exp = $this->model->getAny($sql_exp);
                $data_exp = [];
                if (!empty($Res_exp)) {
                    while ($row_exp = mysqli_fetch_array($Res_exp, MYSQLI_ASSOC)) {
                        $data_exp = $row_exp;
                    }


                $data = array_merge($data_exp,$data);
                $orderID = $data['id'];
                }
                # 筛选修改后收货人信息
                $sql_sda = "select  * from shop_delivery_address where orders_id = $orderID order by createdt desc limit 1";
                $orderRes_sda = $this->model->getAny($sql_sda);
                $data_sda = [];
                if (!empty($orderRes_sda)) {
                    while ($row_sda = mysqli_fetch_array($orderRes_sda, MYSQLI_ASSOC)) {
                        $data_sda = $row_sda;
                    }
                }

                if($data_sda && is_array($data_sda) && count($data_sda) > 0){
                    $data['receiver'] = $data_sda['receiver_name'];
                    $data['receiver_tel'] = $data_sda['receiver_tel'];
                    $data['receiver_address'] = $data_sda['receiver_address'];
                }


                $res = json_decode($data['push_response_data'],true);
                $express_type = $data['express_type']?$data['express_type']:'';
                $express_mobile = $data['express_mobile']?$data['express_mobile']:'';

                if($data['status'] < 3){
                    $data['status_code'] = $data['status'];
                    if($data['status'] == 1 && $data['bstatus'] == 0){
                        $str = '指派失败：错误信息 ';
                        if($express_type == 'sf'){
                            $msg = $str.$res['error_msg'];
                        }elseif ($express_type == 'dd'){
                            $msg = $str.$res['msg'];
                        }elseif ($express_type == 'ss'){
                            $msg = $str.$res['msg'];
                        }
                        $data['status'] = $msg;
                    }else{
                        $data['status'] = '尚未配送中 ，无法获取信息，请稍后再试！';
                    }
                }else{
                    $data['status_code'] = $data['status'];
                    $data['status'] = Data::$_express_status[$data['status']];
                }
                $distance = $data['distance'];

                if($data['express_type'] == 'self'){
                    $distance = $data['distance'];
                }elseif($data['express_type'] == 'sf'){
                    $distance = isset($res['result']['delivery_distance_meter'])?$res['result']['delivery_distance_meter']:$data['distance'];
                }elseif($data['express_type'] == 'ss'){
                    $distance = isset($res['data']['distanceTotal'])? $res['data']['distanceTotal']:$data['distance'];
                }elseif($data['express_type'] == 'dd'){
                    $distance = isset($res['result']['distance'])? $res['result']['distance']:$data['distance'];
                }
                $data['distance'] = round($distance,2).' 米';
                $data['express_fee'] += $data['tip'];

                $remark = '';
                if($data['customre_memo']){
                    $remark .= '买家备注：'.$data['customre_memo'].';';
                }
                if($data['seller_remarks']){
                    $remark .= '卖家备注：'.$data['seller_remarks'].';';
                }

                if($data['shop_express_remark']){
                    $remark .= '指派备注：'.$data['shop_express_remark'].';';
                }

                if($data['tip_remark']){
                    $remark .= '小费备注：'.$data['tip_remark'].';';
                }
                $data['remark'] = $remark;
                //$data['express_type'] =$data['express_type'].'aa';// empty($data['express_type']) ? Data::$_express_type['no']:Data::$_express_type[$data['express_type']];
                unset($data['longitude']);
                unset($data['latitude']);
                unset($data['push_response_data']);
                unset($data['customre_memo']);
                unset($data['seller_remarks']);
                unset($data['shop_express_remark']);
                unset($data['shop_remark']);
                unset($data['bid']);
                unset($data['id']);
                unset($data['shop_no']);
                unset($data['shop_name']);
                unset($data['ph_no']);
                unset($data['bstatus']);
                unset($data['tip']);
                $data['express_type'] = empty($express_type)?'':Data::$_express_type_admin[$express_type];
                $data['express_mobile'] = $express_mobile;
            }else{
                $data = [];
            }

            $resule = json_encode(['errcode' => 0, 'errormsg ' => '','data'=>$data],JSON_UNESCAPED_UNICODE);
            $res = json_encode($orderDatas, JSON_UNESCAPED_UNICODE);
            $log->lwrite('reception:' . $res.'response:'.$resule);
            echo $resule;exit;
        }else{
            $resule = json_encode(['errcode' => 1, 'errormsg ' => '未知版本'],JSON_UNESCAPED_UNICODE);
            $res = json_encode($orderDatas, JSON_UNESCAPED_UNICODE);
            $log->lwrite('reception:' . $res.'response:'.$resule);
            echo $resule;exit;
        }

    }

    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }
}